import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

import { getRoleJson, _getRoleList } from "../src/utils/permission";
import { asyncRouterMap } from "../src/router/index";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login", "/reg"]; // no redirect whitelist

// 设置前置守卫
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  if (to.path.toLowerCase() == "/login" || to.path.toLowerCase() == "/reg") {
    next();
  } else {
    let { state, commit } = store;
    // 如果添加过直接next()
    if (state.isAddRouter) {
      next();
    } else {
      // 如果没添加
      try {
        let token = localStorage.getItem("household_token");
        if (token) {
          // 从接口获取权限列表,roleList 得到的是对应角色的路由表
          let roleList = await getRoleJson(token);
          // _getRoleList 接收两个参数: 1、asyncRouterMap 是完整的路由表 2、roleList 是当前角色能够访问到的路由
          let list = _getRoleList(asyncRouterMap, roleList);
          router.addRoutes(list);
          // 改变状态，表示已经配置过权限
          commit("update", { name: "isAddRouter", value: true });
          // 把筛选后的权限存入vuex里，用于渲染左侧菜单
          commit("update", { name: "asyncRoutes", value: list });
          // console.log(path);
          next({ path: list[0].children[0].path });
        } else {
          next({ path: "/login" });
        }
      } catch (e) {
        next({ path: "/login" });
        console.log(e);
      }
    }
  }
});
router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
